
$(function(){
	
	get('system/label/getAll', function(data){
		if(data.success){
			new Vue({
				el: '.searchWordsGroup',
				data: data,
				methods: {
					clickBtn: function(txt){
						var words = $('#words').val();
						if(words.indexOf(txt)<0){
							if(isEmpty(words)){
								$('#words').val(txt);
							}else {
								$('#words').val(words+';'+txt);
							}
						}else {
							$.message({message:'“'+txt+'”已存在', type:'warning'});
						}
					}
				}
			});
		}else {
			spop(data.result, 'error');
		}
	});
	
	var resourcesTable = $('#resourcesTable').DataTable({
		dom: '<"top"fl<"clear">>rt<"bottom"ip<"clear">>',
		lengthMenu: [10, 25, 50, 75, 100],
		pageLength: 10,
		language: dtlanguage,
		ordering: true,
		order: [[6,'desc']],//表示初期第6列降序排序
		processing: true,
		serverSide: true,
		ajax: {
			url: 'system/resource/getList',
			type: 'get',
			dataType: 'json',
			// 传给服务器的数据，可以添加我们自己的查询参数
            data: function (param) {
                var data = {
                	draw: param.draw,
                	search: param.search.value,
                	limit: param.length,
                	offset: param.start,
                	sort: param.columns[param.order[0].column].data,
                	isDesc: param.order[0].dir==='desc'
                }
                console.log(data);
                return data;
            },
            //预先处理服务器端返回的数据，修改成DT能用格式 draw、recordsTotal、recordsFiltered、data。
            dataFilter: function(text, type){
            	if(!isEmpty(text)){
            		var json = JSON.parse(text);//字符串转json
            		if (json.success) {
            			var qbean = json.result;
                    	var data = {
                    		draw: json.other,
                    		recordsTotal: qbean.itemCount,
                    		recordsFiltered: qbean.itemCount,
                    		data: qbean.result
                    	}
                    	console.log(data);
                    	text = JSON.stringify(data);//json转字符串
            		}
            	}
            	return text;//返回字符串
            },
            //用于处理服务器端返回的数据。 dataSrc是DataTable特有的
            dataSrc: function(data){
            	if(data.data==null){
            		return '';
            	}else {
            		return data.data;
            	}
            }
		},
	
		rowId: 'resourceId',
		columns: [
			{
				data: 'resourceName',
				title: '资源名称',
				defaultContent: '--',
				orderable: false,
				render: shotContent
			},{
				data: 'resourceType',
				title: '类型',
				defaultContent: '--',
				orderable: false,
				render: shotContent
			},{
				data: 'resourceLength',
				title: '大小',
				defaultContent: '--',
				orderable: true,
				render: fileSize
			},{
				data: 'resourceIntroduction',
				title: '资源简介',
				defaultContent: '--',
				orderable: false,
				render: shotContent
			},{
				data: 'searchKeyWords',
				title: '检索词',
				defaultContent: '--',
				orderable: false,
				render: shotContent
			},{
				data: 'downloadAmount',
				title: '下载量',
				defaultContent: '--',
				orderable: true
			},{
				data: 'createTime',
				title: '上传时间',
				defaultContent: '--',
				orderable: true,
				render: shotContent
			}
		],
		columnDefs: [
			{
				targets: 7,
				title: '操作',
				orderable: false,
				render: function (data, type, row, meta) {
					var txt = '下载';
					if(row.pathType==1){
						txt='跳转';
					}else if(row.pathType==2){
						txt='电驴';
					}else if(row.pathType==3){
						txt='磁力';
					}else if(row.pathType==4){
						txt='迅雷';
					}
					return [
				        '<button class="downloadBtn btn btn-sm btn-success" data-resource="'+row.resourceId+'" data-type="'+row.pathType+'" data-path="'+row.resourcePath+'">',
				            '<i class="fa fa-download"></i>&nbsp;'+txt,
				        '</button>&nbsp;',
				        '<button class="editBtn btn btn-sm btn-info" data-resource="'+row.resourceId+'" data-name="'+row.resourceName+'" data-introduction="'+row.resourceIntroduction+'" data-words="'+row.searchKeyWords+'" data-type="'+row.pathType+'" data-path="'+row.resourcePath+'" data-maxnum="'+row.maxReadNum+'">',
				            '<i class="fa fa-trash-o"></i>&nbsp;编辑',
				        '</button>&nbsp;',
				        '<button class="removeBtn btn btn-sm btn-danger" data-resource="'+row.resourceId+'">',
				            '<i class="fa fa-trash-o"></i>&nbsp;删除',
				        '</button>'
				    ].join('');
                }
			}
		]
	});
	
	//下载/打开
	$('#resourcesTable tbody').on( 'click', 'button.downloadBtn', function () {
		var type = $(this).data('type');
		if(type==0){
			var resourceId = $(this).data('resource');
			window.open($('base').attr('href')+'system/resource/download/'+resourceId);
		}else{
			var path = $(this).data('path');
			window.open(path);
		}
    });
	
	//删除
	$('#resourcesTable tbody').on( 'click', 'button.removeBtn', function () {
    	var resourceId = $(this).data('resource');
		confirm("确定删除吗？", "资源删除将无法恢复！", function (isConfirm) {
            if (isConfirm) {
        		del('system/resource/removeResource/'+resourceId, function(data){
        			if(data.success){
        				$.message({message:'删除操作完成', type:'success'});
        				resourcesTable.ajax.reload(null, false);
        			}else {
        				spop(data.result, 'error');
        			}
        		});
            } else {
                //after click the cancel
            }
        }, {confirmButtonText: '删除', cancelButtonText: '取消'});
    });
	
	//编辑
	$('#resourcesTable tbody').on( 'click', 'button.editBtn', function () {
		$('.info-input').val('');
		
		var resourceId = $(this).data('resource');
		$('#resourceId').val(resourceId);
		
		var resourceName = $(this).data('name');
		$('#resourceName').val(resourceName);
		
		var introduction = $(this).data('introduction');
		$('#introduction').val(introduction);
		
		var words = $(this).data('words');
		$('#words').val(words);
		
		var type = $(this).data('type');
		$('#type').val(type);
		if(type==0){
			$('#pathFormGroup').hide();
		}else{
			$('#pathFormGroup').show();
		}
		
		var path = $(this).data('path');
		$('#path').val(path);
		
		var maxNum = $(this).data('maxnum');
		console.log(maxNum);
		$('#maxNum').val(maxNum);
		
		$('#resource-modal').modal('show');
    });
	//编辑资源信息
	$('#resource-form').submit(function(){
		return false;
	});
	$('#resource-save-btn').click(function(){
		var resourceId = $("#resourceId").val();
		if(isEmpty(resourceId)){
			spop('请重新点开要修改的记录', 'error');
			$('#resource-modal').modal('hide');
			return false;
		}
		var resourceName = $("#resourceName").val();
		if(isEmpty(resourceName)){
			$("#resourceName-label").html("<code>*请输入资源名称*</code>");
			$("#resourceName").focus();
			return false;
		}
		var type = $('#type').val();
		var path = $("#path").val();
		if(type!==0 && isEmpty(path)){
			$("#path-label").html("<code>*请输入资源地址*</code>");
			$("#path").focus();
			return false;
		}
		var introduction = $("#introduction").val();
		if(isEmpty(introduction)){
			$("#introduction-label").html("<code>*请输入资源简介*</code>");
			$("#introduction").focus();
			return false;
		}
		var words = $("#words").val();
		if(isEmpty(words)){
			$("#words-label").html("<code>*请输入搜索关键词*</code>");
			$("#words").focus();
			return false;
		}
		
		var maxNum = $('#maxNum').val();
		if(!isEmpty(maxNum)){
			var reg = /^\d{1,10}$/;//10位以内的数字
			if (!reg.test(maxNum.trim())) {
				$.message({message:'请输入10位以内的正常数字', type:'warning'});
				$('#maxNum').focus();
				return false;
			}
		}
		
		post('system/resource/editResource', function(data){
			if(data.success){
				$.message({message:'修改成功', type:'success'});
				$('.info-input').val('');
				$('#resource-modal').modal("hide");
				resourcesTable.ajax.reload(null, false);
			}else {
				spop(data.result, 'error');
			}
		}, {
			resourceId: resourceId.trim(),
			resourceName: resourceName.trim(),
			introduction: introduction.trim(),
			words: words.trim(),
			path: path.trim(),
			maxReadNum: maxNum.trim()
		});
	});
	
});

/**
 * 表格内容过长
 * @param data
 * @param type
 * @param row
 * @param meta
 * @returns
 */
function shotContent(data, type, row, meta) {
	if(data==null){
		return '--';
	}
    return type === 'display' && data.length > 10 ?
    '<span title="' + data + '">' + data.substr(0, 7) + '...</span>' : data;
}

/**
 * 文件大小单位
 */
var fileSize = function(bytes) {
	if (bytes === 0) return '0 B';
	var k = 1000, // or 1024
        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));
	return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}